package com.nuaa.ange.config;

import cn.hutool.core.map.MapUtil;
import com.nuaa.ange.shiro.AccountRealm;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.DelegatingFilterProxy;


import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author 玦离
 * @description shiro
 * @date 2022/12/7 20:07
 */

@Slf4j
@Configuration
public class ShiroConfig {

    @Bean
    public SecurityManager securityManager(AccountRealm accountRealm){

        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(accountRealm);

        log.info("------------------>securityManager注入成功");

        return securityManager;
    }

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {

        ShiroFilterFactoryBean filterFactoryBean = new ShiroFilterFactoryBean();
        filterFactoryBean.setSecurityManager(securityManager);
        // 配置登录的url和登录成功的url
//        filterFactoryBean.setLoginUrl("/login");
//        filterFactoryBean.setSuccessUrl("/user/center");
//        // 配置未授权跳转页面
//        filterFactoryBean.setUnauthorizedUrl("/error/403");

        Map<String, String> hashMap = new LinkedHashMap<>();

        hashMap.put("/article/**", "roles[user]");
        hashMap.put("/reply/**", "roles[user]");
        hashMap.put("/tag/**", "roles[user]");
        hashMap.put("/message/**", "roles[user]");
        hashMap.put("/article-pic/**", "roles[user]");

        hashMap.put("/login", "anon");
        hashMap.put("/regUser", "anon");
        hashMap.put("/regUserInfo", "anon");

        hashMap.put("/static/**", "anon");
        hashMap.put("/swagger-ui.html", "anon");
        hashMap.put("/swagger-resources/**", "anon");
        hashMap.put("/v2/**", "anon");
        hashMap.put("/webjars/**", "anon");
        hashMap.put("/**", "authc");
        filterFactoryBean.setFilterChainDefinitionMap(hashMap);

        // 配置shiro默认登录界面地址，前后端分离中登录界面跳转应由前端路由控制，后台仅返回json数据
        filterFactoryBean.setLoginUrl("/unauth");

        return filterFactoryBean;

    }


}
